<?php

namespace App\Http\Middleware;

use App;
use App\Http\Contracts\Responsable;
use App\Transformers\ResponseService;
use Closure;
use DB;
use Illuminate\Http\Request;

class Transformer
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        App::setLocale($request->getPreferredLanguage());

        config('app.debug') && logger($request->fullUrl());
        config('app.debug') && DB::enableQueryLog();

        DB::beginTransaction();

        $response = $next($request);

        if ($response instanceof Responsable)

            $response = $response->toResponse($request);

        $response = ResponseService::createFromBase($response);

        $response->isSuccessful() ? DB::commit() : DB::rollBack();

        config('app.debug') && logger(DB::getQueryLog());

        return $response;
    }
}
